using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;

namespace CriticalSystems.Instrumentation.Internal
{
    internal static class ResourceUtilities
    {
        internal static Stream GetEmbeddedResource(string name)
        {
            var assembly = Assembly.GetCallingAssembly();
            return GetEmbeddedResource(assembly, name);
        }

// ReSharper disable MemberCanBePrivate.Global
        internal static Stream GetEmbeddedResource(Assembly assembly, string name)
// ReSharper restore MemberCanBePrivate.Global
        {
            var resourceStream = assembly.GetManifestResourceStream(name);
            return resourceStream;
        }

// ReSharper disable UnusedMember.Global
        internal static Stream GetEmbeddedResource(Type type, string name)
// ReSharper restore UnusedMember.Global
        {
            return GetEmbeddedResource(type.Assembly, type.Namespace + "." + name);
        }

// ReSharper disable UnusedMember.Global
        internal static IList<Stream> GetResources(string namePattern)
// ReSharper restore UnusedMember.Global
        {
            return GetResources(Assembly.GetCallingAssembly(), namePattern);
        }

// ReSharper disable UnusedMember.Global
        internal static IList<Stream> GetResources(Type type, string namePattern)
// ReSharper restore UnusedMember.Global
        {
            return GetResources(type.Assembly, namePattern);
        }

        internal static IList<Stream> GetResources(Assembly assembly, string namePattern)
        {
            var resourceNames = assembly.GetManifestResourceNames();
            var regex = new Regex(namePattern);
            IList<Stream> streams = new List<Stream>();
            foreach (var resourceName in resourceNames)
            {
                if (regex.Match(resourceName).Success)
                {
                    streams.Add(GetEmbeddedResource(assembly, resourceName));
                }
            }
            return streams;
        }
    }
}